#!/usr/bin/env python3
"""
实时监控BudgetAgent和WeatherAgent协商过程
"""

import requests
import json
import time
import threading
from datetime import datetime

class RealTimeNegotiationMonitor:
    """实时协商监控器"""
    
    def __init__(self):
        self.agents = {
            "budget": "http://localhost:7007",
            "weather": "http://localhost:7003"
        }
        self.monitoring = False
        self.negotiation_events = []
    
    def start_monitoring(self):
        """开始监控"""
        self.monitoring = True
        print("🔍 开始实时监控BudgetAgent和WeatherAgent协商...")
        
        # 启动监控线程
        budget_thread = threading.Thread(target=self.monitor_budget_agent)
        weather_thread = threading.Thread(target=self.monitor_weather_agent)
        
        budget_thread.daemon = True
        weather_thread.daemon = True
        
        budget_thread.start()
        weather_thread.start()
    
    def monitor_budget_agent(self):
        """监控BudgetAgent活动"""
        while self.monitoring:
            try:
                # 检查BudgetAgent状态
                response = requests.get(f"{self.agents['budget']}/status", timeout=2)
                if response.status_code == 200:
                    self.log_event("budget", "status_check", "✅ BudgetAgent在线")
                else:
                    self.log_event("budget", "status_check", f"⚠️ BudgetAgent状态异常: {response.status_code}")
            except Exception as e:
                self.log_event("budget", "status_check", f"❌ BudgetAgent连接失败: {e}")
            
            time.sleep(5)  # 每5秒检查一次
    
    def monitor_weather_agent(self):
        """监控WeatherAgent活动"""
        while self.monitoring:
            try:
                # 检查WeatherAgent状态
                response = requests.get(f"{self.agents['weather']}/status", timeout=2)
                if response.status_code == 200:
                    self.log_event("weather", "status_check", "✅ WeatherAgent在线")
                else:
                    self.log_event("weather", "status_check", f"⚠️ WeatherAgent状态异常: {response.status_code}")
            except Exception as e:
                self.log_event("weather", "status_check", f"❌ WeatherAgent连接失败: {e}")
            
            time.sleep(5)  # 每5秒检查一次
    
    def log_event(self, agent, event_type, message):
        """记录事件"""
        event = {
            "timestamp": datetime.now().strftime("%H:%M:%S"),
            "agent": agent,
            "event_type": event_type,
            "message": message
        }
        self.negotiation_events.append(event)
        
        # 实时输出
        print(f"[{event['timestamp']}] {agent.upper()}: {message}")
    
    def trigger_test_negotiation(self):
        """触发测试协商"""
        print("\n🧪 触发测试协商场景...")
        
        # 发送低预算请求给BudgetAgent
        test_request = {
            "type": "collaboration_request",
            "user_requirements": {
                "budget": "100欧元",  # 极低预算
                "destination": "欧洲",
                "duration": "3天",
                "preferences": ["户外活动"]
            },
            "collaboration_context": {
                "purpose": "negotiation_test"
            }
        }
        
        payload = {
            "message": {
                "content": {
                    "text": json.dumps(test_request, ensure_ascii=False)
                }
            }
        }
        
        try:
            print("📤 向BudgetAgent发送低预算测试请求...")
            response = requests.post(
                f"{self.agents['budget']}/a2a/tasks/send",
                json=payload,
                timeout=15
            )
            
            if response.status_code == 200:
                self.log_event("budget", "negotiation_trigger", "✅ 成功触发预算分析")
                
                result = response.json()
                if "artifacts" in result:
                    budget_response_text = result["artifacts"][0]["parts"][0]["text"]
                    budget_response = json.loads(budget_response_text)
                    
                    conflicts = budget_response.get('potential_conflicts', [])
                    self.log_event("budget", "conflict_detection", f"检测到{len(conflicts)}个冲突")
                    
                    for conflict in conflicts:
                        severity = conflict.get('severity', 'unknown')
                        description = conflict.get('description', 'no description')
                        self.log_event("budget", "conflict_detail", f"{severity}: {description}")
                    
                    # 检查是否会触发协商
                    high_conflicts = [c for c in conflicts if c.get('severity') in ['high', 'critical']]
                    if high_conflicts:
                        self.log_event("budget", "negotiation_expected", "🚨 预期将发起对WeatherAgent的协商!")
                        
                        # 等待协商发生
                        time.sleep(2)
                        self.check_weather_negotiation()
                    else:
                        self.log_event("budget", "negotiation_expected", "ℹ️ 预期不会发起协商")
            else:
                self.log_event("budget", "negotiation_trigger", f"❌ 请求失败: {response.status_code}")
                
        except Exception as e:
            self.log_event("budget", "negotiation_trigger", f"❌ 请求异常: {e}")
    
    def check_weather_negotiation(self):
        """检查WeatherAgent是否收到协商"""
        print("🔍 检查WeatherAgent协商处理能力...")
        
        # 模拟协商请求
        test_negotiation = {
            "type": "negotiation_request", 
            "sender": "BudgetAgent",
            "negotiation_context": {
                "issue": "budget_shortfall",
                "severity": "high"
            },
            "proposals": [
                {"option": "test_proposal", "description": "测试提案"}
            ]
        }
        
        payload = {
            "message": {
                "content": {
                    "text": json.dumps(test_negotiation, ensure_ascii=False)
                }
            }
        }
        
        try:
            response = requests.post(
                f"{self.agents['weather']}/a2a/tasks/send",
                json=payload,
                timeout=10
            )
            
            if response.status_code == 200:
                self.log_event("weather", "negotiation_received", "✅ 成功接收协商请求")
                
                result = response.json()
                if "artifacts" in result:
                    weather_response_text = result["artifacts"][0]["parts"][0]["text"]
                    weather_response = json.loads(weather_response_text)
                    
                    if 'error' in weather_response:
                        self.log_event("weather", "negotiation_processing", f"❌ 处理错误: {weather_response['error']}")
                    else:
                        self.log_event("weather", "negotiation_processing", "✅ 协商处理成功")
            else:
                self.log_event("weather", "negotiation_received", f"❌ 协商请求失败: {response.status_code}")
                
        except Exception as e:
            self.log_event("weather", "negotiation_received", f"❌ 协商请求异常: {e}")
    
    def stop_monitoring(self):
        """停止监控"""
        self.monitoring = False
        print("🛑 停止监控")
    
    def print_summary(self):
        """打印监控摘要"""
        print("\n" + "="*80)
        print("📋 协商监控摘要")
        print("="*80)
        
        budget_events = [e for e in self.negotiation_events if e['agent'] == 'budget']
        weather_events = [e for e in self.negotiation_events if e['agent'] == 'weather']
        
        print(f"💰 BudgetAgent事件: {len(budget_events)}个")
        print(f"🌤️ WeatherAgent事件: {len(weather_events)}个")
        
        # 显示重要事件
        important_events = [e for e in self.negotiation_events 
                          if e['event_type'] in ['conflict_detection', 'negotiation_trigger', 'negotiation_received']]
        
        if important_events:
            print(f"\n🎯 重要事件:")
            for event in important_events[-10:]:  # 最近10个重要事件
                print(f"  [{event['timestamp']}] {event['agent'].upper()}: {event['message']}")

def main():
    """主函数"""
    print("🚀 启动实时协商监控器")
    
    monitor = RealTimeNegotiationMonitor()
    
    try:
        # 开始监控
        monitor.start_monitoring()
        
        # 等待一会儿让监控稳定
        time.sleep(2)
        
        # 触发测试协商
        monitor.trigger_test_negotiation()
        
        # 继续监控一段时间
        print("\\n⏳ 监控中...按Ctrl+C停止")
        time.sleep(30)  # 监控30秒
        
    except KeyboardInterrupt:
        print("\\n🛑 收到停止信号")
    finally:
        monitor.stop_monitoring()
        monitor.print_summary()
        print("✅ 监控结束")

if __name__ == "__main__":
    main()